package org.itstec.order.service.impl;

import java.util.Date;
import java.util.UUID;

import org.itstec.base.db.DBBeanBase;
import org.itstec.common.result.R;
import org.itstec.common.security.SHA1Util;
import org.itstec.order.entify.Order;
import org.itstec.order.mapper.OrderMapper;
import org.itstec.order.service.OrderService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;

    public OrderServiceImpl(OrderMapper orderMapper){
        this.orderMapper = orderMapper;
    }

	@Override
    public R<?> create(Order order) {
        R<Order> r = this.get(order);
        if(r.getData() != null){
            return R.code("201","订单已存在，请勿重复下单");
        }
        String orderNo;
        UUID uuid=UUID.randomUUID();
		try {
			orderNo = SHA1Util.shaEncode(uuid.toString());
			if("".equals(orderNo)){
				throw new Exception("订单号加密异常");
			}
		} catch (Exception e) {
			return R.code("202","订单号异常");
		}
        order.setOrderNo(orderNo);
        order.setPayStatus("0");
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        orderMapper.insert(order);
        return R.data(order);
    }

    @Override
    public R<Order> get(Order order) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(Order::getOrderNo,order.getOrderNo());
        Order orderDb = orderMapper.selectOne(orderQueryWrapper);
        if(orderDb == null){
            return R.code("201","订单不存在");
        }
        return R.data(orderDb);
    }

	@Override
	public R<?> copy(long id, int copiesNum) {
		if(copiesNum<=0){
			return R.code("200","检查复制订单数量");
		}
		String sql = "select id from t_orders where id="+id;
		DBBeanBase dbbean = new DBBeanBase(true);
		try{
			int order = dbbean.executeQuery(sql);
			if(order>0){
				sql = "insert into t_orders (product_id,product_name,address) select product_id,product_name,address from t_orders where id="+id;
				for(int i=0; i<=copiesNum; i++){
					dbbean.executeUpdate(sql);
				}
			}
			dbbean.commit();
		}catch(Exception e){
			dbbean.rollback();
			return R.code("500","订单复制异常");
		}finally{
			dbbean.close();
		}
		return R.code("200","订单复制完成");
	}
	
}
